package com.coffee.web.filter;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * XSS拦截过滤器
 *
 * @author Xulg
 * Created in 2019-06-03 14:27
 */
//@Order(value = Ordered.HIGHEST_PRECEDENCE)
//@WebFilter(urlPatterns = "/*", filterName = "xssFilter")
public class XssFilter implements Filter {
    private final static Logger logger = LoggerFactory.getLogger(XssFilter.class);

    private static final String PREFIX_MULTIPART = "multipart";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        logger.info("XssFilter过滤器执行......");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String contentType = servletRequest.getContentType();
        // 文件上传类型请求不拦截
        if (StringUtils.startsWith(contentType, PREFIX_MULTIPART)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        filterChain.doFilter(new XssHttpServletRequestWrapper(request), servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) {
        if (logger.isDebugEnabled()) {
            System.out.println("初始化XssFilter过滤器======================");
            logger.debug("初始化XssFilter过滤器======================");
        }
    }

    @Override
    public void destroy() {
        if (logger.isDebugEnabled()) {
            System.out.println("销毁XssFilter过滤器======================");
            logger.debug("销毁XssFilter过滤器======================");
        }
    }

    private class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
        @SuppressWarnings("WeakerAccess")
        public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
            super(servletRequest);
        }

        @Override
        public String getParameter(String name) {
            return StringEscapeUtils.escapeHtml4(super.getParameter(name));
        }
    }
}
